<?php
	function install_core() {
		global $query;
            
		//Bring the modules to install
            foreach ($query->yaml_docs as $folder => $data) {
			$struct = $data['prototypes'];
      		if (!is_array($struct)) {
				continue;
			}		
                  
			// Foreach to create tables
      		foreach($struct as $module_name => $module_data) {
                  
      			//Check whether I need to create a table for this module
      			if($module_data['fields']) {
                        
      				//Check whether it has a parent
      				if($module_data['parent']) {
                              
      					create_table(PREFIX.$module_name,$module_data['fields'],1); 
                              
      				} else {
                              
      					create_table(PREFIX.$module_name,$module_data['fields']); 
                              
      				}
                              
      			}
                  
                  }
            }
           
	}
	
	function create_table($table_name,$fields,$has_parent = -1) {
		global $query;	
		$sql = "CREATE TABLE IF NOT EXISTS " . $table_name . " (";
            $queries = array();
            $primary_key = "";
		foreach($fields as $field_name => $field_data) {
			//Add the field name to the sql query
			$sql .= $field_name . " ";
			//Check the role of the field
			if($field_data['role'] == "id") {
				$sql .= "INT UNSIGNED NOT NULL AUTO_INCREMENT,";
				//Save the primary key's name
				$primary_key .= $field_name . ", ";
                        $queries[] = "CREATE UNIQUE INDEX ".$table_name."_".$field_name." ON $table_name ($field_name)";
			} 
			elseif($field_data['role'] == "title") {
				$sql .= "VARCHAR(255) NOT NULL,";
			} 
                  elseif($field_data['role'] == "slug") {
				$sql .= "VARCHAR(255) NOT NULL,";
                        $queries[] = "CREATE INDEX ".$table_name."_".$field_name." ON $table_name ($field_name)";
                  }
                  elseif($field_data['role'] == "content") {
				$sql .= "TEXT";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";
			}
			elseif($field_data['role'] == "time") {
				$sql .= "TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,";
			} 
                  elseif($field_data['role'] == "update time") {
				$sql .= "TIMESTAMP NULL,";                  
                  }                  
                  elseif($field_data['type'] == "choice") {
                        $sql .= "ENUM(";
                        foreach ($field_data['choices'] as $choice) {
                              
                              $sql .= "'".$choice."',";
                        }
                        $sql = substr($sql, 0, strlen($sql) - 1);
                        $sql .= ")";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";
                  }
                  elseif($field_data['type'] == 'text') {
                        $sql .= "TEXT ";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";
                  }
                  elseif ($field_data['type'] == 'number') {
				$sql .= "INT ";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";                        
                  }       
                  elseif ($field_data['type'] == 'numbers and letters') {
				$sql .= "VARCHAR(127) ";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";                       
                  } elseif($field_data['type'] == 'date') {
				  	$sql .= "TIMESTAMP ";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";                       
				  }
				else {
				$sql .= "VARCHAR(127) ";
                        if ($field_data['default']) {
                              $sql .= "DEFAULT '".$field_data['default']."'";
                        }
                        $sql .= ",";
			}		
                  if ($field_data['key'] == 'yes') {
				$primary_key .= $field_name . ", ";
                  }
		}
		
		//Check if the current prototype could have a parent
		if($has_parent != -1) {
			$sql .= "_parent_id INT UNSIGNED,";
			$sql .= "_parent_type VARCHAR(255),";
		}
		

		//Add the primary key, if it has one.
		if($primary_key) {
			$sql .= "PRIMARY KEY (" . substr($primary_key, 0, strlen($primary_key) - 2) . ")";
		} else {
			$sql = substr($sql,0,strlen($sql)-1);
		}
		$sql .= ")";
		if($query->db->query($sql)) {
                  foreach ($queries as $this_query) {
                        if (!$query->db->query($this_query)) {
                              // CONTINUEHERE
                             $query->log->error(array('context' => "Installation", 'query' => ''), $query->db->error); 
                        }
                  }
			return 1;
		} else {
			$query->log->error(array('context' => "Installation", 'query' => $query->db->query),"Could not create table " . $table_name);
		}
	}
	
      
      // TOREVIEW If a table is missing, it installs all from ground...
      function check_installation() {
      
            global $query;
                        
            $resultset = $query->db->query("SHOW TABLES");
            
            $tables = array();
            
            while ($table = $query->db->getfield($resultset)) $tables[] = $table;

            foreach ($query->prototypes as $prototype) {
            
                  if ($prototype->_fields) {
                  
                        if ((!in_array(PREFIX . strtolower($prototype->_type), $tables)) 
						    &&(!in_array(PREFIX . $prototype->_type, $tables))){
                        
                              install_core();
                              return;
                              
                        }
                  
                  }
            
            }

      }
      
      function installation_procedure() {
            
            global $query;
            
            // Iterate each prototype, check if the prototype has field, check its state in the database
            foreach ($query->prototypes as $prototype) {
                  
                  // If has fields we must check the table
                  if ($prototype->_fields) {
                        
                        // If the table exists, check if the fields match the roles and types
                        if ($description = $query->db->query("describe ".PREFIX.$prototype->_type)) {

                              $fields = array();
                              
                              while ($row = $query->db->getarray($description)) {

                                    $fields[$row['fields']] = $row;
                                    
                              }
                              
                              check_table($prototype, $fields);
                              
                        } 
                        
                        // If the table doesn't exists, create it
                        else {
                              
                              // TODO: Create the function for create table
                              create_table($prototype);
                              
                        }
                        
                  }
                  
            }
            
      }
      
      /*
      function check_table($prototype, $fields) {
            
            
            
      }
      
      function create_table($prototype) {
            
            
            
      }
      */
     
?>